package com.SouthernWall_404.AgeRight.Common.Network.Packets.S2C;

import com.SouthernWall_404.AgeRight.Common.API.Capability.Missions;
import com.SouthernWall_404.AgeRight.Common.API.Capability.Provider.MissionsProvider;
import net.minecraft.client.Minecraft;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.world.entity.player.Player;
import net.minecraftforge.network.NetworkEvent;

import java.util.function.Supplier;

public class MissionsSyncPacket {
    private final CompoundTag missionsData;

    public MissionsSyncPacket(CompoundTag missionsData) {
        this.missionsData = missionsData;
    }

    public static void encode(MissionsSyncPacket msg, FriendlyByteBuf buffer) {
        buffer.writeNbt(msg.missionsData);
    }

    public static MissionsSyncPacket decode(FriendlyByteBuf buffer) {
        return new MissionsSyncPacket(buffer.readNbt());
    }

    public static void handle(MissionsSyncPacket msg, Supplier<NetworkEvent.Context> ctx) {
        ctx.get().enqueueWork(() -> {
            // 在客户端线程执行
            Player player = Minecraft.getInstance().player;
            if (player != null) {
                player.getCapability(MissionsProvider.MISSIONS_CAPABILITY).ifPresent(missions -> {
                    missions.deserializeNBT(msg.missionsData);
                    System.out.println("客户端接收到任务数据同步");
                });
            }
        });
        ctx.get().setPacketHandled(true);
    }
}